#!/bin/bash

# Nginx Offline Installation Script
# Function: Compile and install nginx-1.28.0 with systemctl service configuration
# Compatible: Anolis OS 7.9 and other offline environments
# Author: System Administrator
# Date: $(date +%Y-%m-%d)
#
# Usage Instructions:
# 1. Place nginx-1.28.0.tar.gz in the same directory as this script
# 2. CRITICAL: Install build tools first (script will auto-install, or install manually):
#    - For Anolis OS 7.9: yum install gcc gcc-c++ make
#    - For CentOS/RHEL: yum install gcc gcc-c++ make  
#    - For Ubuntu/Debian: apt-get install gcc g++ make
# 3. Development libraries (auto-installed by script):
#    - pcre-devel zlib-devel openssl-devel (RedHat series)
#    - libpcre3-dev zlib1g-dev libssl-dev (Debian series)
# 4. Run with root privileges: sudo ./nginx_install.sh
# 5. Installation path: /opt/RadMedical/product/tool/nginx
#
# IMPORTANT NOTES:
# - Script will auto-install all dependencies before compilation
# - If "C compiler cc is not found" error occurs, install gcc first
# - Script includes gcc, gcc-c++ (or g++), and make
# - Only essential nginx modules will be compiled
# - Compilation process may take a long time

set -e  # Exit immediately on error

# Color definitions
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Logging functions
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if running as root user
check_root() {
    if [[ $EUID -ne 0 ]]; then
        log_error "This script requires root privileges to run"
        exit 1
    fi
}

# Check if nginx source package exists
check_nginx_source() {
    local nginx_tar="nginx-1.28.0.tar.gz"
    if [[ ! -f "$nginx_tar" ]]; then
        log_error "nginx source package $nginx_tar not found, please ensure file is in current directory"
        exit 1
    fi
    log_info "Found nginx source package: $nginx_tar"
}

# Check offline environment
check_offline_environment() {
    log_info "Checking system environment..."
    
    # Detect system type
    if [[ -f /etc/os-release ]]; then
        source /etc/os-release
        log_info "Detected system: $PRETTY_NAME"
        
        if [[ "$ID" == "anolis" ]] || [[ "$ID" == "centos" ]] || [[ "$ID" == "rhel" ]]; then
            log_info "System type: RedHat series (Anolis/CentOS/RHEL)"
            return 0
        elif [[ "$ID" == "ubuntu" ]] || [[ "$ID" == "debian" ]]; then
            log_info "System type: Debian series (Ubuntu/Debian)"
            return 1
        else
            log_warn "Unknown system type: $ID"
            return 2
        fi
    else
        log_warn "Unable to detect system type"
        return 2
    fi
}

# Check necessary build tools
check_build_tools() {
    log_info "Checking build tools..."
    
    local missing_tools=()
    local critical_error=false
    
    # Check C compiler
    if ! command -v gcc >/dev/null 2>&1; then
        missing_tools+=("gcc")
        critical_error=true
    fi
    
    # Check C++ compiler
    if ! command -v g++ >/dev/null 2>&1; then
        missing_tools+=("g++/gcc-c++")
        log_warn "C++ compiler (g++/gcc-c++) not found, some features may not work"
        # Don't set critical_error for C++ compiler as nginx can usually compile without it
    fi
    
    # Check make
    if ! command -v make >/dev/null 2>&1; then
        missing_tools+=("make")
        critical_error=true
    fi
    
    # Check if cc is available (some systems use cc instead of gcc)
    if ! command -v cc >/dev/null 2>&1 && ! command -v gcc >/dev/null 2>&1; then
        log_error "No C compiler found! Neither 'cc' nor 'gcc' is available."
        critical_error=true
    fi
    
    if [[ $critical_error == true ]]; then
        log_error "Critical build tools are missing:"
        for tool in "${missing_tools[@]}"; do
            log_error "  - $tool"
        done
        
        log_info ""
        log_info "SOLUTION: Install the missing tools manually:"
        log_info ""
        log_info "For Anolis OS 7.9 / CentOS / RHEL:"
        log_info "  yum install gcc gcc-c++ make"
        log_info ""
        log_info "For Ubuntu / Debian:"
        log_info "  apt-get install gcc g++ make"
        log_info ""
        log_info "If you cannot install packages, try:"
        log_info "  1. Check if gcc is installed but not in PATH"
        log_info "  2. Look for alternative compilers (clang, etc.)"
        log_info "  3. Install from source if package manager is not available"
        log_info ""
        
        read -p "Do you want to continue anyway? (y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            log_error "Installation cancelled due to missing critical tools"
            exit 1
        fi
    else
        log_info "Essential build tools check passed"
        
        # Show which compiler will be used
        if command -v gcc >/dev/null 2>&1; then
            log_info "Using GCC compiler: $(gcc --version | head -n1)"
        elif command -v cc >/dev/null 2>&1; then
            log_info "Using CC compiler: $(cc --version | head -n1)"
        fi
    fi
}

# Attempt to install build dependencies (offline environment)
install_dependencies() {
    log_info "Checking build dependencies..."
    
    local system_type=$(check_offline_environment)
    
    case $system_type in
        0) # RedHat series
            log_info "Detected RedHat series system (Anolis/CentOS/RHEL)"
            log_warn "Please manually install the following packages if not already installed:"
            log_warn "  gcc gcc-c++ make automake autoconf libtool"
            log_warn "  pcre-devel zlib-devel openssl-devel"
            ;;
        1) # Debian series
            log_info "Detected Debian series system (Ubuntu/Debian)"
            log_warn "Please manually install the following packages if not already installed:"
            log_warn "  build-essential libpcre3-dev zlib1g-dev libssl-dev"
            ;;
        *) # Unknown system
            log_warn "Unknown system type, please ensure build tools are installed"
            ;;
    esac
    
    # Check installation results
    check_build_tools
}

# Create nginx user
create_nginx_user() {
    log_info "Creating nginx user..."
    
    if id "nginx" &>/dev/null; then
        log_warn "nginx user already exists"
    else
        useradd -r -s /bin/false -d /var/cache/nginx -c "nginx user" nginx
        log_info "nginx user created successfully"
    fi
}

# Extract nginx source code
extract_nginx_source() {
    log_info "Extracting nginx source package..."
    
    if [[ -d "nginx-1.28.0" ]]; then
        log_warn "nginx-1.28.0 directory already exists, removing old directory..."
        rm -rf nginx-1.28.0
    fi
    
    tar -xzf nginx-1.28.0.tar.gz
    cd nginx-1.28.0
    
    log_info "nginx source extraction completed"
}

# Configure nginx compilation options
configure_nginx() {
    log_info "Configuring nginx compilation options..."
    
    # Create installation directory and set permissions
    mkdir -p /opt/RadMedical/product/tool/nginx
    # Set permissions for installation directory
    chmod 755 /opt/RadMedical/product/tool/nginx 2>/dev/null || true
    
    # Configure compilation options with essential modules only
    if ./configure \
        --prefix=/opt/RadMedical/product/tool/nginx \
        --sbin-path=/opt/RadMedical/product/tool/nginx/sbin/nginx \
        --conf-path=/opt/RadMedical/product/tool/nginx/conf/nginx.conf \
        --error-log-path=/opt/RadMedical/product/tool/nginx/logs/error.log \
        --http-log-path=/opt/RadMedical/product/tool/nginx/logs/access.log \
        --pid-path=/opt/RadMedical/product/tool/nginx/logs/nginx.pid \
        --lock-path=/opt/RadMedical/product/tool/nginx/logs/nginx.lock \
        --http-client-body-temp-path=/opt/RadMedical/product/tool/nginx/temp/client_temp \
        --http-proxy-temp-path=/opt/RadMedical/product/tool/nginx/temp/proxy_temp \
        --http-fastcgi-temp-path=/opt/RadMedical/product/tool/nginx/temp/fastcgi_temp \
        --http-uwsgi-temp-path=/opt/RadMedical/product/tool/nginx/temp/uwsgi_temp \
        --http-scgi-temp-path=/opt/RadMedical/product/tool/nginx/temp/scgi_temp \
        --user=nginx \
        --group=nginx \
        --with-http_ssl_module \
        --with-http_realip_module \
        --with-http_gzip_static_module \
        --with-http_stub_status_module \
        --with-threads \
        --with-stream \
        --with-stream_ssl_module \
        --with-file-aio \
        --with-http_v2_module; then
        log_info "nginx configuration completed successfully"
    else
        log_error "nginx configuration failed!"
        log_info ""
        log_info "Common causes and solutions:"
        log_info ""
        log_info "1. C compiler not found:"
        log_info "   Error: 'C compiler cc is not found'"
        log_info "   Solution: Install gcc - yum install gcc"
        log_info ""
        log_info "2. Missing development libraries:"
        log_info "   Error: 'PCRE library is not found'"
        log_info "   Solution: Install pcre-devel - yum install pcre-devel"
        log_info ""
        log_info "3. Missing zlib library:"
        log_info "   Error: 'zlib library is not found'"
        log_info "   Solution: Install zlib-devel - yum install zlib-devel"
        log_info ""
        log_info "4. Missing OpenSSL library:"
        log_info "   Error: 'OpenSSL library is not found'"
        log_info "   Solution: Install openssl-devel - yum install openssl-devel"
        log_info ""
        log_info "5. Missing make tool:"
        log_info "   Error: 'make: command not found'"
        log_info "   Solution: Install make - yum install make"
        log_info ""
        log_info "Complete installation command for Anolis OS 7.9:"
        log_info "  yum install gcc gcc-c++ make pcre-devel zlib-devel openssl-devel"
        log_info ""
        exit 1
    fi
}

# Compile and install nginx
compile_install_nginx() {
    log_info "Starting nginx compilation..."
    
    # Get CPU core count for parallel compilation
    local cpu_cores=$(nproc)
    log_info "Using $cpu_cores CPU cores for compilation"
    
    # Compilation phase
    if make -j$cpu_cores; then
        log_info "nginx compilation successful"
    else
        log_error "nginx compilation failed"
        log_info "Possible causes:"
        log_info "1. Missing necessary build tools or development libraries"
        log_info "2. Insufficient system resources"
        log_info "3. Corrupted source package"
        log_info ""
        log_info "Suggested solutions:"
        log_info "1. Check if complete build environment is installed"
        log_info "2. Try single-threaded compilation: make"
        log_info "3. Check system memory and disk space"
        exit 1
    fi
    
    log_info "Starting nginx installation..."
    if make install; then
        log_info "nginx installation successful"
    else
        log_error "nginx installation failed"
        log_info "Possible causes:"
        log_info "1. Insufficient permissions on target directory"
        log_info "2. Insufficient disk space"
        log_info "3. Incorrect installation path configuration"
        exit 1
    fi
}

# Create necessary directories and set permissions
setup_directories() {
    log_info "Creating necessary directories and setting permissions..."
    
    # Create necessary directories if they don't exist
    mkdir -p /opt/RadMedical/product/tool/nginx/logs
    mkdir -p /opt/RadMedical/product/tool/nginx/conf
    mkdir -p /opt/RadMedical/product/tool/nginx/sbin
    mkdir -p /opt/RadMedical/product/tool/nginx/html
    mkdir -p /opt/RadMedical/product/tool/nginx/temp/client_temp
    mkdir -p /opt/RadMedical/product/tool/nginx/temp/proxy_temp
    mkdir -p /opt/RadMedical/product/tool/nginx/temp/fastcgi_temp
    mkdir -p /opt/RadMedical/product/tool/nginx/temp/uwsgi_temp
    mkdir -p /opt/RadMedical/product/tool/nginx/temp/scgi_temp
    
    # Set ownership and permissions for installation directory
    chown -R nginx:nginx /opt/RadMedical/product/tool/nginx
    
    # Set directory permissions (755 for directories, 644 for config files)
    chmod -R 755 /opt/RadMedical/product/tool/nginx
    
    # Set specific permissions for binaries
    if [[ -f /opt/RadMedical/product/tool/nginx/sbin/nginx ]]; then
        chmod 755 /opt/RadMedical/product/tool/nginx/sbin/nginx
    fi
    
    # Set specific permissions for config files
    if [[ -f /opt/RadMedical/product/tool/nginx/conf/nginx.conf ]]; then
        chmod 644 /opt/RadMedical/product/tool/nginx/conf/nginx.conf
    fi
    
    # Set specific permissions for log files
    touch /opt/RadMedical/product/tool/nginx/logs/error.log 2>/dev/null || true
    touch /opt/RadMedical/product/tool/nginx/logs/access.log 2>/dev/null || true
    chmod 644 /opt/RadMedical/product/tool/nginx/logs/*.log 2>/dev/null || true
    chown nginx:nginx /opt/RadMedical/product/tool/nginx/logs/*.log 2>/dev/null || true
    
    # Ensure nginx user can write to temp directories
    chmod -R 770 /opt/RadMedical/product/tool/nginx/temp 2>/dev/null || true
    
    log_info "Directory permissions setup completed"
}

# Create optimized nginx configuration based on server resources
create_optimized_nginx_config() {
    log_info "Creating optimized nginx configuration based on server resources..."
    
    # Detect server resources
    local cpu_cores=$(nproc)
    local total_mem=$(free -m | awk 'NR==2{print $2}')
    
    # Calculate optimal worker processes (typically 1 per CPU core)
    local worker_processes=$cpu_cores
    
    # Calculate optimal connections per worker based on memory
    # Formula: total_mem * 1024 / avg_page_size / worker_count
    # Average page size ~20KB for small pages
    local worker_connections
    if [[ $total_mem -gt 4096 ]]; then
        worker_connections=8192
    elif [[ $total_mem -gt 2048 ]]; then
        worker_connections=4096
    elif [[ $total_mem -gt 1024 ]]; then
        worker_connections=2048
    else
        worker_connections=1024
    fi
    
    # Calculate keepalive_timeout based on server type
    local keepalive_timeout=65
    
    log_info "Configuration parameters:"
    log_info "  Worker processes: $worker_processes"
    log_info "  Worker connections: $worker_connections"
    log_info "  Keepalive timeout: ${keepalive_timeout}s"
    
    # Create optimized nginx configuration
    cat > /opt/RadMedical/product/tool/nginx/conf/nginx.conf << EOF
# Nginx Configuration File
# Optimized for: ${cpu_cores} CPU cores, ${total_mem}MB memory
# Generated on: $(date '+%Y-%m-%d %H:%M:%S')

# User and group for worker processes
# Note: Master process runs as root to bind to privileged ports
# Worker processes will drop privileges and run as nginx user
user nginx nginx;

# Worker processes - set to number of CPU cores
worker_processes $worker_processes;

# Error log
error_log  /opt/RadMedical/product/tool/nginx/logs/error.log warn;
pid        /opt/RadMedical/product/tool/nginx/logs/nginx.pid;

# Events block - optimized for performance
events {
    worker_connections $worker_connections;
    use epoll;
    multi_accept on;
}

# HTTP server configuration
http {
    include       mime.types;
    default_type  application/octet-stream;

    # Logging format
    log_format main '\$remote_addr - \$remote_user [\$time_local] "\$request" '
                    '\$status \$body_bytes_sent "\$http_referer" '
                    '"\$http_user_agent" "\$http_x_forwarded_for"';

    access_log  /opt/RadMedical/product/tool/nginx/logs/access.log  main;

    # Performance optimizations
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   $keepalive_timeout;
    keepalive_requests  100;
    types_hash_max_size 2048;
    server_tokens       off;

    # Gzip compression
    gzip                on;
    gzip_vary           on;
    gzip_proxied        any;
    gzip_comp_level      6;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript application/x-javascript;
    gzip_min_length      1000;
    gzip_disable        "msie6";

    # Buffer sizes
    client_body_buffer_size      128k;
    client_max_body_size         10m;
    client_header_buffer_size    1k;
    large_client_header_buffers  4 4k;
    output_buffers               1 32k;
    postpone_output              1460;

    # Timeouts
    client_body_timeout           12;
    client_header_timeout         12;
    send_timeout                  10;

    # File handle limits
    open_file_cache max=1000 inactive=20s;
    open_file_cache_valid        30s;
    open_file_cache_min_uses      2;
    open_file_cache_errors        on;

    # FastCGI optimizations
    fastcgi_connect_timeout       300;
    fastcgi_send_timeout           300;
    fastcgi_read_timeout           300;
    fastcgi_buffer_size            64k;
    fastcgi_buffers                4 64k;
    fastcgi_busy_buffers_size     128k;
    fastcgi_temp_file_write_size  256k;
    fastcgi_cache_valid           200 302 10m;
    fastcgi_cache_valid           301      1h;
    fastcgi_cache_valid           any      1m;
    fastcgi_cache_min_uses        1;
    fastcgi_cache_use_stale       error timeout invalid_header http_500;

    # Proxy optimizations
    proxy_connect_timeout          300;
    proxy_send_timeout             300;
    proxy_read_timeout              300;
    proxy_buffer_size               64k;
    proxy_buffers                   4 64k;
    proxy_busy_buffers_size        128k;
    proxy_temp_file_write_size     256k;
    proxy_redirect                 off;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;

    # Server block - default configuration
    server {
        listen       80;
        server_name  localhost;

        root         /opt/RadMedical/product/tool/nginx/html;
        index        index.html index.htm;

        # Logging
        access_log   /opt/RadMedical/product/tool/nginx/logs/access.log main;
        error_log    /opt/RadMedical/product/tool/nginx/logs/error.log;

        # Location block for root
        location / {
            try_files \$uri \$uri/ =404;
        }

        # Location block for static assets
        location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
            expires 365d;
            add_header Cache-Control "public, immutable";
        }

        # Health check endpoint
        location /health {
            access_log off;
            return 200 "healthy\n";
            add_header Content-Type text/plain;
        }

        # Status page (requires --with-http_stub_status_module)
        location /status {
            stub_status on;
            access_log off;
            allow 127.0.0.1;
            deny all;
        }

        # Deny access to hidden files
        location ~ /\. {
            deny all;
            access_log off;
            log_not_found off;
        }

        # Error pages
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /opt/RadMedical/product/tool/nginx/html;
        }
    }
}
EOF

    # Set proper permissions for config file
    chown nginx:nginx /opt/RadMedical/product/tool/nginx/conf/nginx.conf
    chmod 644 /opt/RadMedical/product/tool/nginx/conf/nginx.conf
    
    log_info "Optimized nginx configuration created successfully"
}

# Create default HTML files
create_default_html_files() {
    log_info "Creating default HTML files..."
    
    # Create index.html
    cat > /opt/RadMedical/product/tool/nginx/html/index.html << 'HTML_EOF'
<!DOCTYPE html>
<html>
<head>
    <title>Welcome to nginx!</title>
    <meta charset="utf-8">
    <style>
        body {
            width: 35em;
            margin: 0 auto;
            font-family: Tahoma, Verdana, Arial, sans-serif;
        }
    </style>
</head>
<body>
    <h1>Welcome to nginx!</h1>
    <p>If you see this page, the nginx web server is successfully installed and
    working. Further configuration is required.</p>
    
    <p>For online documentation and support please refer to
    <a href="http://nginx.org/">nginx.org</a>.<br/>
    Commercial support is available at
    <a href="http://nginx.com/">nginx.com</a>.</p>
    
    <p><em>Thank you for using nginx.</em></p>
</body>
</html>
HTML_EOF

    # Create 50x.html error page
    cat > /opt/RadMedical/product/tool/nginx/html/50x.html << 'HTML_EOF'
<!DOCTYPE html>
<html>
<head>
    <title>Error</title>
    <meta charset="utf-8">
    <style>
        body {
            width: 35em;
            margin: 0 auto;
            font-family: Tahoma, Verdana, Arial, sans-serif;
        }
    </style>
</head>
<body>
    <h1>An error occurred.</h1>
    <p>Sorry, the page you are looking for is currently unavailable.<br/>
    Please try again later.</p>
    <p>If you are the system administrator of this resource then you should check
    the error log for details.</p>
    <p><em>Faithfully yours, nginx.</em></p>
</body>
</html>
HTML_EOF

    # Set proper permissions
    chown nginx:nginx /opt/RadMedical/product/tool/nginx/html/*.html 2>/dev/null || true
    chmod 644 /opt/RadMedical/product/tool/nginx/html/*.html 2>/dev/null || true
    
    log_info "Default HTML files created successfully"
}

# Create systemctl service file
create_systemd_service() {
    log_info "Creating systemctl service file..."
    
    cat > /etc/systemd/system/nginx.service << 'EOF'
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/opt/RadMedical/product/tool/nginx/logs/nginx.pid
ExecStartPre=/opt/RadMedical/product/tool/nginx/sbin/nginx -t
ExecStart=/opt/RadMedical/product/tool/nginx/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true
# Run master process as root to bind to privileged ports
# Worker processes will run as nginx user (configured in nginx.conf)

[Install]
WantedBy=multi-user.target
EOF

    log_info "systemctl service file created successfully"
}

# Configure nginx auto-start on boot
enable_nginx_service() {
    log_info "Configuring nginx auto-start on boot..."
    
    # Reload systemd configuration
    systemctl daemon-reload
    
    # Enable nginx service
    systemctl enable nginx
    
    log_info "nginx auto-start configuration completed"
}

# Test nginx configuration
test_nginx_config() {
    log_info "Testing nginx configuration..."
    
    if /opt/RadMedical/product/tool/nginx/sbin/nginx -t; then
        log_info "nginx configuration test passed"
    else
        log_error "nginx configuration test failed"
        exit 1
    fi
}

# Final permission check before starting nginx
final_permission_check() {
    log_info "Performing final permission check before starting nginx..."
    
    # Check and set permissions for key directories
    local key_dirs=(
        "/opt/RadMedical/product/tool/nginx"
        "/opt/RadMedical/product/tool/nginx/logs"
        "/opt/RadMedical/product/tool/nginx/conf"
        "/opt/RadMedical/product/tool/nginx/sbin"
        "/opt/RadMedical/product/tool/nginx/html"
        "/opt/RadMedical/product/tool/nginx/temp"
    )
    
    for dir in "${key_dirs[@]}"; do
        if [[ -d "$dir" ]]; then
            log_info "Checking permissions for: $dir"
            chown -R nginx:nginx "$dir" 2>/dev/null || true
            chmod 755 "$dir" 2>/dev/null || true
        fi
    done
    
    # Check executable file
    if [[ -f /opt/RadMedical/product/tool/nginx/sbin/nginx ]]; then
        chmod 755 /opt/RadMedical/product/tool/nginx/sbin/nginx
        chown nginx:nginx /opt/RadMedical/product/tool/nginx/sbin/nginx
    fi
    
    # Check and set permissions for PID file location
    mkdir -p /opt/RadMedical/product/tool/nginx/logs
    chown nginx:nginx /opt/RadMedical/product/tool/nginx/logs
    chmod 755 /opt/RadMedical/product/tool/nginx/logs
    
    # Ensure temp directories are writable
    chmod -R 770 /opt/RadMedical/product/tool/nginx/temp 2>/dev/null || true
    chown -R nginx:nginx /opt/RadMedical/product/tool/nginx/temp 2>/dev/null || true
    
    log_info "Final permission check completed"
}

# Start nginx service
start_nginx_service() {
    log_info "Starting nginx service..."
    
    # Perform final permission check before starting
    final_permission_check
    
    systemctl start nginx
    
    # Check service status
    if systemctl is-active --quiet nginx; then
        log_info "nginx service started successfully"
    else
        log_error "nginx service failed to start"
        systemctl status nginx
        exit 1
    fi
}

# Display installation information
show_installation_info() {
    log_info "=========================================="
    log_info "nginx installation completed!"
    log_info "=========================================="
    log_info "Installation path: /opt/RadMedical/product/tool/nginx"
    log_info "Configuration file: /opt/RadMedical/product/tool/nginx/conf/nginx.conf"
    log_info "Log directory: /opt/RadMedical/product/tool/nginx/logs/"
    log_info "HTML directory: /opt/RadMedical/product/tool/nginx/html/"
    log_info ""
    log_info "Configuration Status:"
    log_info "  - Optimized nginx configuration has been applied"
    log_info "  - Configuration is tuned based on your server resources"
    log_info "  - CPU cores: $(nproc)"
    log_info "  - Memory: $(free -m | awk 'NR==2{print $2}')MB"
    log_info ""
    log_info "Service Commands:"
    log_info "  Status: systemctl status nginx"
    log_info "  Start:  systemctl start nginx"
    log_info "  Stop:   systemctl stop nginx"
    log_info "  Restart: systemctl restart nginx"
    log_info "  Reload: systemctl reload nginx"
    log_info ""
    log_info "Testing:"
    log_info "  Test config: /opt/RadMedical/product/tool/nginx/sbin/nginx -t"
    log_info "  Health check: curl http://localhost/health"
    log_info "  Status page: curl http://localhost/status"
    log_info "=========================================="
}

# Check system resources
check_system_resources() {
    log_info "Checking system resources..."
    
    # Check disk space
    local available_space=$(df /tmp | awk 'NR==2 {print $4}')
    local required_space=500000  # 500MB in KB
    
    if [[ $available_space -lt $required_space ]]; then
        log_warn "Insufficient disk space: Available ${available_space}KB, Required ${required_space}KB"
        log_warn "Consider cleaning up disk space or choosing another installation location"
    else
        log_info "Disk space check passed: Available ${available_space}KB"
    fi
    
    # Check memory
    local total_mem=$(free -m | awk 'NR==2{print $2}')
    if [[ $total_mem -lt 1024 ]]; then
        log_warn "System memory is low: ${total_mem}MB, compilation process may be slow"
    else
        log_info "Memory check passed: ${total_mem}MB"
    fi
    
    # Check CPU core count
    local cpu_cores=$(nproc)
    log_info "CPU core count: $cpu_cores"
    
    log_info "System resource check completed"
}

# Pre-installation check for offline environment
pre_install_check() {
    log_info "=========================================="
    log_info "nginx offline installation environment check"
    log_info "=========================================="
    
    # Check system environment
    check_offline_environment
    
    # Check system resources
    check_system_resources
    
    log_info ""
    log_info "Offline installation instructions:"
    log_info "1. This script is suitable for Anolis OS 7.9 and other offline environments"
    log_info "2. Please ensure the system has installed essential build tools (gcc, gcc-c++, make)"
    log_info "3. Script will auto-install dependencies if available"
    log_info "4. Installation process may take a long time"
    log_info "5. Only essential nginx modules will be compiled"
    log_info ""
    
    read -p "Confirm to continue installation? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        log_info "User cancelled installation"
        exit 0
    fi
    
    log_info "=========================================="
}

# Install dependencies from local source
install_local_dependencies() {
    log_info "=========================================="
    log_info "Installing dependencies from local source"
    log_info "=========================================="
    
    local system_type=$(check_offline_environment)
    
    case $system_type in
        0) # RedHat series
            log_info "Installing dependencies for RedHat series (Anolis/CentOS/RHEL)..."
            
            # Install all required packages directly
            yum install -y gcc gcc-c++ make pcre-devel zlib-devel openssl-devel 2>&1 | tee /tmp/nginx_deps_install.log
            
            if [[ $? -eq 0 ]]; then
                log_info "Successfully installed dependencies: gcc gcc-c++ make pcre-devel zlib-devel openssl-devel"
            else
                log_error "Failed to install dependencies using yum"
                log_warn "Please check the log file: /tmp/nginx_deps_install.log"
                log_warn "Try running manually: yum install -y gcc gcc-c++ make pcre-devel zlib-devel openssl-devel"
            fi
            ;;
        1) # Debian series
            log_info "Installing dependencies for Debian series (Ubuntu/Debian)..."
            
            # Update package list and install all required packages
            apt-get update 2>&1 | tee /tmp/nginx_deps_update.log
            apt-get install -y gcc g++ make libpcre3-dev zlib1g-dev libssl-dev 2>&1 | tee /tmp/nginx_deps_install.log
            
            if [[ $? -eq 0 ]]; then
                log_info "Successfully installed dependencies: gcc g++ make libpcre3-dev zlib1g-dev libssl-dev"
            else
                log_error "Failed to install dependencies using apt-get"
                log_warn "Please check the log file: /tmp/nginx_deps_install.log"
                log_warn "Try running manually: apt-get install -y gcc g++ make libpcre3-dev zlib1g-dev libssl-dev"
            fi
            ;;
        *)
            log_warn "Unknown system type, cannot auto-install dependencies"
            log_warn "Please manually install the following packages:"
            log_warn "  For RedHat series: yum install -y gcc gcc-c++ make pcre-devel zlib-devel openssl-devel"
            log_warn "  For Debian series: apt-get install -y gcc g++ make libpcre3-dev zlib1g-dev libssl-dev"
            ;;
    esac
    
    log_info "=========================================="
}

# Quick compiler check before starting
quick_compiler_check() {
    log_info "Performing quick compiler check..."
    
    if ! command -v gcc >/dev/null 2>&1 && ! command -v cc >/dev/null 2>&1; then
        log_error "CRITICAL ERROR: No C compiler found!"
        log_error "Neither 'gcc' nor 'cc' is available in the system."
        log_info ""
        log_info "This error means:"
        log_info "  ./configure: error: C compiler cc is not found"
        log_info ""
        log_info "SOLUTION: Install GCC compiler first:"
        log_info ""
        log_info "For Anolis OS 7.9:"
        log_info "  yum install gcc gcc-c++"
        log_info ""
        log_info "For CentOS/RHEL:"
        log_info "  yum install gcc gcc-c++"
        log_info ""
        log_info "For Ubuntu/Debian:"
        log_info "  apt-get install gcc g++"
        log_info ""
        log_info "After installing gcc, run this script again."
        log_info ""
        exit 1
    fi
    
    if ! command -v make >/dev/null 2>&1; then
        log_error "CRITICAL ERROR: make command not found!"
        log_info ""
        log_info "SOLUTION: Install make tool:"
        log_info "  yum install make"
        log_info ""
        exit 1
    fi
    
    log_info "Compiler check passed - proceeding with installation"
}

# Main function
main() {
    log_info "Starting nginx-1.28.0 installation..."
    
    # Check root privileges first (needed for dependency installation)
    check_root
    
    # Install dependencies from local source
    install_local_dependencies
    
    # Quick compiler check after dependency installation
    quick_compiler_check
    
    # Pre-installation check for offline environment
    pre_install_check
    
    # Check nginx source package
    check_nginx_source
    
    # Create nginx user
    create_nginx_user
    
    # Extract nginx source code
    extract_nginx_source
    
    # Configure nginx compilation options
    configure_nginx
    
    # Compile and install nginx
    compile_install_nginx
    
    # Setup directory permissions
    setup_directories
    
    # Create optimized nginx configuration based on server resources
    create_optimized_nginx_config
    
    # Create default HTML files
    create_default_html_files
    
    # Create systemctl service file
    create_systemd_service
    
    # Configure auto-start on boot
    enable_nginx_service
    
    # Test nginx configuration
    test_nginx_config
    
    # Start nginx service
    start_nginx_service
    
    # Display installation information
    show_installation_info
    
    log_info "nginx installation script execution completed!"
}

# Execute main function
main "$@"